import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/main/lz_hot_cakes/view/lz_hot_cakes_page.dart';
import 'package:shopping_group/main/lz_mall/view/lz_mall_home_page.dart';
import 'package:shopping_group/modle/login/ui/user_login_page.dart';
import 'package:shopping_group/modle/notice/ui/forum_page.dart';
import 'package:shopping_group/modle/person/entity/soujianren_entity.dart';
import 'package:shopping_group/modle/person/ui/person_page.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/shared_preferences_util.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'main_page.dart';

class BottomMenuPage extends StatefulWidget {
  @override
  _BottomMenuPageState createState() => _BottomMenuPageState();
}

class _BottomMenuPageState extends State<BottomMenuPage>
    with AutomaticKeepAliveClientMixin {
  DateTime lastPopTime;
  StreamSubscription _blackSubscription;
  StreamSubscription _toSubscription;
  StreamSubscription _updateSubscription;
  List<Widget> listViews = [
    MainPage(),
    LzHotCakesPage(),
    LzMallHomePage(),
    ForumPage(),
    PersonPage(),
  ];
  int _index = 0;
  int _changePage = 0;
  String version = '';
  String appPath = '';
  StreamSubscription _rsetLoginSubscription;
  @override
  void initState() {
    super.initState();
    _index = BaseConstant.changePageIndex;
    _changePage = BaseConstant.changePageIndex;
    _rsetLoginSubscription = eventBus.on<RsetLoginEvent>().listen((event) {
      if (BaseConstant.isLogin) {
        BotToast.closeAllLoading();
        _loginOut();
      }
    });
    _blackSubscription = eventBus.on<BlackPageEvent>().listen((event) {
      setState(() {
        _index = _changePage;
      });
    });

    _toSubscription = eventBus.on<ToChangePageEvent>().listen((event) {
      setState(() {
        _index = BaseConstant.changePageIndex;
        _changePage = BaseConstant.changePageIndex;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return WillPopScope(
      onWillPop: () async {
        // 点击返回键的操作
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
          lastPopTime = DateTime.now();
          BotToast.showText(text: '再按一次退出');
          return false;
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          SystemNavigator.pop();
          return true;
        }
      },
      child: Scaffold(
        body: IndexedStack(
          index: _index,
          children: listViews,
        ),
        bottomNavigationBar: BottomNavigationBar(
          // unselectedFontSize: Dimens.FONT_SIZE_10,
          // selectedFontSize: Dimens.FONT_SIZE_10,
          items: [
            BottomNavigationBarItem(
              // activeIcon:
              //     WidgetUtils.getImageAsset('homed', width: 24.0, height: 24.0),
              // icon:
              //     WidgetUtils.getImageAsset('home', width: 24.0, height: 24.0),
              icon: Icon(
                Icons.home,
                color: _index == 0 ? Colours.themeColor : Colours.gray_91,
                size: 24,
              ),
              title: WidgetUtils.getTextColorView(
                  '首页',
                  _index == 0 ? Colours.themeColor : Colours.gray_91,
                  Dimens.FONT_SIZE_10),
            ),
            BottomNavigationBarItem(
              // activeIcon: WidgetUtils.getImageAsset('addressed',
              //     width: 24.0, height: 24.0),
              // icon: WidgetUtils.getImageAsset('address',
              //     width: 24.0, height: 24.0),
              icon: Icon(
                Icons.apps,
                color: _index == 1 ? Colours.themeColor : Colours.gray_91,
                size: 24,
              ),
              title: WidgetUtils.getTextColorView(
                  '热销',
                  _index == 1 ? Colours.themeColor : Colours.gray_91,
                  Dimens.FONT_SIZE_10),
            ),
            BottomNavigationBarItem(
              activeIcon: WidgetUtils.getImageAsset('pp_logo_2',
                  width: 24.0, height: 24.0),
              icon: WidgetUtils.getImageAsset('pp_logo_1',
                  width: 24.0, height: 24.0),
              title: WidgetUtils.getTextColorView(
                  '利正生活',
                  _index == 2 ? Colours.themeColor : Colours.gray_91,
                  Dimens.FONT_SIZE_10),
            ),
            BottomNavigationBarItem(
              activeIcon: WidgetUtils.getImageAsset('sq_logo_2',
                  width: 24.0, height: 24.0),
              icon: WidgetUtils.getImageAsset('sq_logo_1',
                  width: 24.0, height: 24.0),
              title: WidgetUtils.getTextColorView(
                '社区',
                _index == 3 ? Colours.themeColor : Colours.gray_91,
                Dimens.FONT_SIZE_10,
              ),
            ),
            BottomNavigationBarItem(
              // activeIcon: WidgetUtils.getImageAsset('statemented',
              //     width: 24.0, height: 24.0),
              // icon: WidgetUtils.getImageAsset('statement',
              //     width: 24.0, height: 24.0),
              icon: Icon(
                Icons.account_box,
                color: _index == 4 ? Colours.themeColor : Colours.gray_91,
                size: 24,
              ),
              title: WidgetUtils.getTextColorView(
                  '我的',
                  _index == 4 ? Colours.themeColor : Colours.gray_91,
                  Dimens.FONT_SIZE_10),
            ),
          ],
          currentIndex: _index,
          type: BottomNavigationBarType.fixed,
          onTap: (int index) {
            setState(() {
              if (!BaseConstant.isLogin &&
                  (3 == index || 1 == index || 4 == index || 2 == index)) {
                if (Utils.isWeixin()) {
                  BotToast.showText(text: '请重新打开链接，自动登录');
                } else {
                  RouteUtil.goParameter(UserLoginPage(),
                      pageName: PageConstance.LOGIN_PAGE);
                }

                _index = 0;
                _changePage = index;
              } else {
                _index = index;
                eventBus.fire(ResetMoneyEvent());
              }
              BaseConstant.changePageIndex = _index;
            });
          },
        ),
      ),
    );
  }

  Future _loginOut() async {
    showDialog(
        context: context,
        builder: (context) {
          return showAlertDialog();
        }).then((var result) {
      if (null == result) {
        return;
      }
      if (result is String && 'yes' == result) {
        RouteUtil.popUntil(PageConstance.MAIN_PAGE);
        ;
      }
    });
  }

  _clear() {
    setState(() {
      BaseConstant.isLogin = false;
      BaseConstant.code = '';
      BaseConstant.name = '';
      BaseConstant.nickname = '';
      BaseConstant.idCard = '';
      BaseConstant.token = '';
      BaseConstant.capitalAccount = '0';
      BaseConstant.integralAccount = '0';
      BaseConstant.allAccount = '0';
      BaseConstant.reBuyQuanAcct = '0';
      BaseConstant.adressEntity = SouJianRenEntity();
      BaseConstant.changePageIndex = 0;
      SharedPreferencesUtil.addShare('password', '');
      BaseConstant.isUpdate = false;
      eventBus.fire(ToChangePageEvent());
    });
  }

  Widget showAlertDialog() {
    return AlertDialog(
      title: WidgetUtils.getTextColorView(
          '重复登录', Colors.black, Dimens.FONT_SIZE_18),
      content: WidgetUtils.getTextColorView(
          '已有账号登录', Colors.black, Dimens.FONT_SIZE_16),
      actions: <Widget>[
        FlatButton(
          onPressed: () {
            Navigator.of(context).pop('yes');
            _clear();
          },
          child: WidgetUtils.getTextColorView(
              '关闭', Colors.black, Dimens.FONT_SIZE_16),
        ),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    _blackSubscription?.cancel();
    _toSubscription?.cancel();
    _updateSubscription?.cancel();
    _rsetLoginSubscription?.cancel();
    super.dispose();
  }
}
